package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SyDatasetInfo;
import com.ruoyi.system.domain.SyEngineer;
import com.ruoyi.system.domain.SyFileInfo;
import com.ruoyi.system.domain.SyProject;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 项目信息表Controller
 * 
 * @author SYGIS
 * @date 2023-09-13
 */
@RestController
@RequestMapping("/system/project")
public class SyProjectController extends BaseController {

    @Autowired
    private ISyProjectService syProjectService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISyFileInfoService fileInfoService;

    @Autowired
    private ISyEngineerService engineerService;

    @Autowired
    private ISyDatasetInfoService datasetInfoService;

    @GetMapping("/getBindDatasetProjectList")
    public AjaxResult getBindDatasetProjectList(SyProject param) {
        SyDatasetInfo dataset = datasetInfoService.selectSyDatasetInfoByUuid(param.getUuid());
        List<SyProject> list = new ArrayList<>();
        if(dataset!=null){
            if(dataset.getProjectIds()!=null){
                if(dataset.getProjectIds().length()>0){
                    String[] ids = dataset.getProjectIds().split(",");
                    if(ids.length>0) {
                        for (String id : ids) {
                            if(id.replaceAll(" ","").length()>0){
                                SyProject project = syProjectService.selectSyProjectByUuid(id);
                                if(project!=null){
                                    project.setHasRole(1);
                                    list.add(project);
                                }
                            }
                        }
                    }
                }
            }
        }
        return AjaxResult.success(list);
    }
    @GetMapping("/getDatasetProjectList")
    public AjaxResult getDatasetProjectList(SyProject param) {
        List<SyProject> list = syProjectService.selectDatasetProjectList();
        if(list.size()>0){
            for(SyProject project:list){
                List<SyDatasetInfo> datasets = datasetInfoService.selectDatasetByUuidAndProjectId(param.getUuid(),project.getUuid());
                if(datasets.size()>0){
                    project.setHasRole(1);
                }else{
                    project.setHasRole(0);
                }
            }
        }
        return AjaxResult.success(list);
    }

    @PostMapping("/saveDatasetProjects")
    public AjaxResult saveDatasetProjects(@RequestBody SyProject param){
        SyDatasetInfo dataset = datasetInfoService.selectSyDatasetInfoByUuid(param.getUuid());
        if(dataset!=null){
            if(dataset.getProjectIds()!=null){
                String[] ids = param.getIds().split(",");
                if(ids.length>0) {
                    for (String id : ids) {
                        if(dataset.getProjectIds().indexOf(id)<0){
                            dataset.setProjectIds(dataset.getProjectIds()+","+id);
                        }
                    }
                }
            }else{
                dataset.setProjectIds(param.getIds());
            }
        }
        datasetInfoService.updateSyDatasetInfo(dataset);
        return AjaxResult.success();
    }

    @PostMapping("/unhookDatasetProject")
    public AjaxResult unhookDatasetProject(@RequestBody SyProject param){
        SyDatasetInfo dataset = datasetInfoService.selectSyDatasetInfoByUuid(param.getUuid());
        if(dataset!=null){
            String projectIds = dataset.getProjectIds().replaceAll(","+param.getIds(),"").replaceAll(param.getIds(),"");
            dataset.setProjectIds(projectIds);
            datasetInfoService.updateSyDatasetInfo(dataset);
        }
        return AjaxResult.success();
    }

    @PostMapping("/createProjectNo")
    public AjaxResult createProjectNo(){
        SimpleDateFormat format = new SimpleDateFormat("YYYYMMddHHmmssSSS");
        String projectNo = "YNJT-PROJECT-"+format.format(new Date());
        Map<Object,Object> res = new HashMap<>();
        res.put("projectNo",projectNo);
        return AjaxResult.success(res);
    }

    @GetMapping("/getRoleProjectList")
    public AjaxResult getRoleProjectList(SyProject param) {
        List<SyProject> list = new ArrayList<>();
        List<SyProject> unbindRoleList = syProjectService.selectUnbindRoleList(param.getRoleIds());
        List<SyProject> bindRoleList = syProjectService.selectBindRoleList(param.getRoleIds());
        if(unbindRoleList.size()>0){
            for (SyProject res:unbindRoleList){
                res.setHasRole(0);
                list.add(res);
            }
        }
        if(bindRoleList.size()>0){
            for (SyProject res:bindRoleList){
                res.setHasRole(1);
                list.add(res);
            }
        }
        return AjaxResult.success(list);
    }

    @GetMapping("/getBindRoleProjectList")
    public AjaxResult getBindRoleProjectList(SyProject param) {
        List<SyProject> list = new ArrayList<>();
        List<SyProject> bindRoleList = syProjectService.selectBindRoleList(param.getRoleIds());
        if(bindRoleList.size()>0){
            for (SyProject res:bindRoleList){
                res.setHasRole(1);
                list.add(res);
            }
        }
        return AjaxResult.success(list);
    }

    @PostMapping("/saveRoleProjects")
    public AjaxResult saveRoleProjects(@RequestBody SyProject param){
        String[] ids = param.getIds().split(",");
        if(ids.length>0) {
            for (String id : ids) {
                SyProject project = syProjectService.selectSyProjectByUuid(id);
                if(project!=null){
                    if(project.getRoleIds()!=null){
                        if(project.getRoleIds().indexOf(param.getRoleIds())<0){
                            project.setRoleIds(project.getRoleIds()+","+param.getRoleIds());
                        }
                    }else{
                        project.setRoleIds(param.getRoleIds());
                    }
                    syProjectService.updateSyProject(project);
                }
            }
        }
        return AjaxResult.success();
    }

    @PostMapping("/unhookRoleProject")
    public AjaxResult unhookRoleProject(@RequestBody SyProject param) {
        SyProject project = syProjectService.selectSyProjectByUuid(param.getUuid());
        if(project!=null){
            if(project.getRoleIds()!=null){
                String roleIds = project.getRoleIds().replaceAll(","+param.getRoleIds(),"").replaceAll(param.getRoleIds(),"");
                project.setRoleIds(roleIds);
                syProjectService.updateSyProject(project);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 查询项目信息表列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SyProject syProject) {
        startPage();
        List<SyProject> list = syProjectService.selectSyProjectList(syProject);
        if(list.size()>0){
            for(SyProject project:list){
                if(project.getChargerId()!=null){
                    SysUser user = userService.selectUserById(project.getChargerId());
                    if(user!=null){
                        project.setChargerName(user.getNickName());
                    }
                }

                if(project.getDeptId()!=null){
                    SysDept dept = deptService.selectDeptById(project.getDeptId());
                    if(dept!=null){
                        project.setDeptName(dept.getDeptName());
                    }
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出项目信息表列表
     */
    @Log(title = "项目信息表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SyProject syProject) {
        List<SyProject> list = syProjectService.selectSyProjectList(syProject);
        ExcelUtil<SyProject> util = new ExcelUtil<SyProject>(SyProject.class);
        util.exportExcel(response, list, "项目信息表数据");
    }

    /**
     * 获取项目信息表详细信息
     */
    @GetMapping(value = "/{uuid}")
    public AjaxResult getInfo(@PathVariable("uuid") String uuid) {
        SyProject project = syProjectService.selectSyProjectByUuid(uuid);
        if(project!=null){
            if(project.getMaterialAttach()!=null){
                List<SyFileInfo> attachList = getAttachList(project.getMaterialAttach());
                project.setAttachList(attachList);
            }
            if(project.getChargerId()!=null){
                SysUser user = userService.selectUserById(project.getChargerId());
                if(user!=null){
                    project.setChargerName(user.getNickName());
                }
            }
            if(project.getDeptId()!=null){
                SysDept dept = deptService.selectDeptById(project.getDeptId());
                if(dept!=null){
                    project.setDeptName(dept.getDeptName());
                }
            }
            if(project.getCreateBy()!=null){
                SysUser user = userService.selectUserById(Long.parseLong(project.getCreateBy()));
                if(user!=null){
                    project.setCreator(user.getNickName());
                }
            }
        }
        return success(project);
    }

    public List<SyFileInfo> getAttachList(String attachUrl){
        String[] attachArray = null;
        if(attachUrl!=null){
            String url = attachUrl.replaceAll(" ","");
            if(url.length()>0){
                attachArray = attachUrl.split(",");
            }
        }
        List<SyFileInfo> list = new ArrayList<>();
        if(attachArray!=null){
            if(attachArray.length>0){
                for(String url:attachArray){
                    SyFileInfo fileInfo = new SyFileInfo();
                    fileInfo.setUrl(url);
                    List<SyFileInfo> files = fileInfoService.selectSyFileInfoList(fileInfo);
                    SyFileInfo file = files.get(0);
                    if(file!=null){
                        file.setName(file.getOriginName());
                    }
                    list.add(file);
                }
            }
        }
        return list;
    }

    /**
     * 新增项目信息表
     */
    @Log(title = "项目信息表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SyProject syProject) {
        return toAjax(syProjectService.insertSyProject(syProject));
    }

    @PostMapping("/processStartProject")
    public AjaxResult processStartProject(@RequestBody SyProject syProject) {
        SyProject project = syProjectService.selectSyProjectByUuid(syProject.getUuid());
        if(project!=null){
            project.setStatus(2);
            syProjectService.updateSyProject(project);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的项目信息");
        }
    }

    @PostMapping("/processDeleteProject")
    public AjaxResult processDeleteProject(@RequestBody SyProject syProject) {
        SyProject project = syProjectService.selectSyProjectByUuid(syProject.getUuid());
        if(project!=null){
            syProjectService.deleteSyProjectByUuid(syProject.getUuid());
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的项目信息");
        }
    }

    @PostMapping("/processRestartProject")
    public AjaxResult processRestartProject(@RequestBody SyProject syProject) {
        SyProject project = syProjectService.selectSyProjectByUuid(syProject.getUuid());
        if(project!=null){
            project.setStatus(2);
            syProjectService.updateSyProject(project);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的项目信息");
        }
    }

    @PostMapping("/processFinishProject")
    public AjaxResult processFinishProject(@RequestBody SyProject syProject) {
        SyProject project = syProjectService.selectSyProjectByUuid(syProject.getUuid());
        if(project!=null){
            project.setStatus(3);
            syProjectService.updateSyProject(project);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的项目信息");
        }
    }

    @PostMapping("/processNullifyProject")
    public AjaxResult processNullifyProject(@RequestBody SyProject syProject) {
        SyProject project = syProjectService.selectSyProjectByUuid(syProject.getUuid());
        if(project!=null){
            project.setStatus(4);
            syProjectService.updateSyProject(project);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的项目信息");
        }
    }

    @PostMapping("/processInitProject")
    public AjaxResult processInitProject(@RequestBody SyProject syProject) {
        SyProject project = syProjectService.selectSyProjectByUuid(syProject.getUuid());
        if(project!=null){
            project.setStatus(1);
            syProjectService.updateSyProject(project);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的项目信息");
        }
    }

    @PostMapping("/editProject")
    public AjaxResult editProject(@RequestBody SyProject syProject) {
        if(syProject.getUuid()==null){ //新增
            // 创建项目
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            syProject.setUuid(uuid);
            syProject.setCreateBy(SecurityUtils.getLoginUser().getUserId().toString());
            syProject.setCreateTime(new Date());
            syProject.setStatus(1);
            syProjectService.insertSyProject(syProject);
            // 给工程挂接项目
            if(syProject.getEngineerIds()!=null){
                String[] engineerIds = syProject.getEngineerIds().split(",");
                if(engineerIds.length>0){
                    for(String engineerId:engineerIds){
                        SyEngineer engineer = engineerService.selectSyEngineerByUuid(engineerId);
                        if(engineer!=null){
                            engineer.setProjectId(uuid);
                            engineerService.updateSyEngineer(engineer);
                        }
                    }
                }
            }
        }else{ //修改
            syProject.setUpdateBy(SecurityUtils.getLoginUser().getUserId().toString());
            syProject.setUpdateTime(new Date());
            syProjectService.updateSyProject(syProject);
            // 给工程挂接项目
            if(syProject.getEngineerIds()!=null){
                String[] engineerIds = syProject.getEngineerIds().split(",");
                if(engineerIds.length>0){
                    for(String engineerId:engineerIds){
                        SyEngineer engineer = engineerService.selectSyEngineerByUuid(engineerId);
                        if(engineer!=null){
                            engineer.setProjectId(syProject.getUuid());
                            engineerService.updateSyEngineer(engineer);
                        }
                    }
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 修改项目信息表
     */
    @Log(title = "项目信息表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SyProject syProject) {
        return toAjax(syProjectService.updateSyProject(syProject));
    }

    /**
     * 删除项目信息表
     */
    @Log(title = "项目信息表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{uuids}")
    public AjaxResult remove(@PathVariable String[] uuids) {
        return toAjax(syProjectService.deleteSyProjectByUuids(uuids));
    }

    @GetMapping("/getProjectList")
    public AjaxResult getProjectList(){
        List<SyProject> list = syProjectService.selectProjectList4Select();
        return AjaxResult.success(list);
    }
}
